package com.competition.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.competition.entity.AgriculturalTraining;
import com.competition.entity.AgriculturalTrainingDetail;
import com.competition.resp.ResponseResult;
import com.competition.service.AgriculturalTrainingDetailService;
import com.competition.service.AgriculturalTrainingService;
import com.upyun.UpException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/agriculturalTrainingDetail")
public class AgriculturalTrainingDetailController {
    @Autowired
    private AgriculturalTrainingDetailService agriculturalTrainingDetailService;

    @Autowired
    private AgriculturalTrainingService agriculturalTrainingService;

    @Autowired
    CommonController commonController;

    @Value("${yCatalogue}")
    private String yCatalogue;

    private String basePath = "agricultural-training";



    @PostMapping("/queryAgriculturalTrainingDetailList")
    public ResponseResult<Object> queryAgriculturalTrainingDetailList(@RequestBody HashMap<String,Object> params){
        if(params.get("page")==null||params.get("pageSize")==null){
            return new ResponseResult<Object>(400,"参数错误",null);
        }
        QueryWrapper<AgriculturalTrainingDetail> objectQueryWrapper = new QueryWrapper<>();
        int page = Integer.parseInt(params.get("page").toString());
        int pageSize = Integer.parseInt(params.get("pageSize").toString());
        params.put("limit",pageSize);
        params.put("offset",(page - 1) * pageSize);
        if(params.get("trainingDetailTime") != null && params.get("trainingDetailTime") instanceof List){
            List<?> list = (List<?>) params.get("trainingDetailTime");
            if (list.size() == 2) {
                List<String> stringList = (List<String>) list;
                params.put("startTime", stringList.get(0));
                params.put("endTime",stringList.get(1));
            }

        }
        List<AgriculturalTrainingDetail> agriculturalTrainingDetailList = agriculturalTrainingDetailService.queryAgriculturalTrainingDetailList(params);
        HashMap<String, Object> resMap = new HashMap<>();
        long count = agriculturalTrainingDetailService.count();
        resMap.put("total",count);
        resMap.put("agriculturalTrainingDetailList",agriculturalTrainingDetailList);
        return new ResponseResult<Object>(200,"获取农业培训列表成功",resMap);
    }

    @GetMapping("/queryAgriculturalTrainingDetailById")
    public ResponseResult<Object> queryAgriculturalTrainingDetailById(@RequestParam HashMap<String,Object> params){
        if (params == null || params.get("trainingDetailId") == null){
            return new ResponseResult<Object>(400,"参数错误",null);
        }
        AgriculturalTrainingDetail agriculturalTrainingDetail = agriculturalTrainingDetailService.queryAgriculturalTrainingDetailById(params.get("trainingDetailId").toString());
        return new ResponseResult<Object>(200,"获取培训详情成功",agriculturalTrainingDetail);
    }

    @PostMapping("/addAgriculturalTrainingDetail")
    @Transactional
    public ResponseResult<Object> addAgriculturalTrainingDetail(@RequestParam  HashMap<String,Object> body,@RequestPart(value = "file",required = false) MultipartFile file) throws UpException, IOException {
        if(body == null || body.isEmpty()){
            return new ResponseResult<Object>(400,"没有传参",null);
        }
        UUID uuid = UUID.randomUUID();
        AgriculturalTraining agriculturalTraining = new AgriculturalTraining();
        AgriculturalTrainingDetail agriculturalTrainingDetail = new AgriculturalTrainingDetail();

        try {
            agriculturalTraining.setAgriculturalTrainingId(uuid.toString());
            agriculturalTraining.setAgriculturalTrainingCount(0);
            agriculturalTraining.setAgriculturalTrainingTitle(body.get("agriculturalTrainingTitle").toString());
            agriculturalTraining.setAgriculturalTrainingPrice(Integer.parseInt(body.get("agriculturalTrainingPrice").toString()));

            agriculturalTrainingDetail.setTrainingDetailId(uuid.toString().substring(1) + "x");
            agriculturalTrainingDetail.setAgriculturalTrainingId(agriculturalTraining.getAgriculturalTrainingId());
            agriculturalTrainingDetail.setTrainingDetailAddress(body.get("trainingDetailAddress").toString());
            agriculturalTrainingDetail.setTrainingDetailTime(body.get("trainingDetailTime").toString());
            agriculturalTrainingDetail.setTrainingDetailType(body.get("trainingDetailType").toString());
        }catch (Exception e){
            return new ResponseResult<Object>(400,"参数缺失",null);
        }
        if(body.get("trainingDetailIntroduce") != null){
            agriculturalTrainingDetail.setTrainingDetailIntroduce(body.get("trainingDetailIntroduce").toString());
        }
        if(file != null){
            String filename = file.getOriginalFilename();
            assert filename != null;
            int dotIndex = filename.lastIndexOf('.');
            String suffix = filename.substring(dotIndex + 1);
            ResponseResult responseResult = commonController.uploadImg(file, basePath, suffix);
            if(responseResult.getCode()!=200){
                return new ResponseResult<Object>(500,"文件上传失败");
            }
            agriculturalTraining.setAgriculturalTrainingImg("https://img.cjz.red/"+this.yCatalogue + "/"+basePath+"/" + responseResult.getData().toString());
        }
        agriculturalTrainingService.save(agriculturalTraining);
        agriculturalTrainingDetailService.save(agriculturalTrainingDetail);
        return new ResponseResult<Object>(200,"添加培训详情成功",null);
    }


    @PutMapping("/modifyAgriculturalTrainingDetail")
    @Transactional
    public ResponseResult<Object> modifyAgriculturalTrainingDetail(@RequestParam  HashMap<String,Object> body,@RequestPart(value = "file",required = false) MultipartFile file) throws UpException, IOException {
        if(body == null || body.isEmpty() || body.get("trainingDetailId") == null){
            return new ResponseResult<Object>(400,"参数错误",null);
        }
        AgriculturalTraining agriculturalTraining = new AgriculturalTraining();
        AgriculturalTrainingDetail agriculturalTrainingDetail = new AgriculturalTrainingDetail();
        try {
            agriculturalTraining.setAgriculturalTrainingTitle(body.get("agriculturalTrainingTitle").toString());
            agriculturalTraining.setAgriculturalTrainingPrice(Integer.parseInt(body.get("agriculturalTrainingPrice").toString()));

            agriculturalTrainingDetail.setTrainingDetailAddress(body.get("trainingDetailAddress").toString());
            agriculturalTrainingDetail.setTrainingDetailTime(body.get("trainingDetailTime").toString());
            agriculturalTrainingDetail.setTrainingDetailType(body.get("trainingDetailType").toString());
        }catch (Exception e){
            return new ResponseResult<Object>(400,"参数缺失",null);
        }
        if(body.get("trainingDetailIntroduce") != null){
            agriculturalTrainingDetail.setTrainingDetailIntroduce(body.get("trainingDetailIntroduce").toString());
        }
        if(file != null){
            String filename = file.getOriginalFilename();
            assert filename != null;
            int dotIndex = filename.lastIndexOf('.');
            String suffix = filename.substring(dotIndex + 1);
            ResponseResult responseResult = commonController.uploadImg(file, basePath, suffix);
            if(responseResult.getCode()!=200){
                return new ResponseResult<Object>(500,"文件上传失败");
            }
            AgriculturalTraining serviceOne = agriculturalTrainingService.getOne(new QueryWrapper<AgriculturalTraining>().eq("agricultural_training_id", body.get("agriculturalTrainingId").toString()));
            if(serviceOne != null && serviceOne.getAgriculturalTrainingImg()!=null && !serviceOne.getAgriculturalTrainingImg().isEmpty()){
                String[] strings = serviceOne.getAgriculturalTrainingImg().split(basePath);
                commonController.deleteImg(basePath, strings[1]);
            }
            agriculturalTraining.setAgriculturalTrainingImg("https://img.cjz.red/"+this.yCatalogue + "/"+basePath+"/" + responseResult.getData().toString());

        }
        agriculturalTrainingService.update(agriculturalTraining,new QueryWrapper<AgriculturalTraining>().eq("agricultural_training_id", body.get("agriculturalTrainingId").toString()));
        agriculturalTrainingDetailService.update(agriculturalTrainingDetail,new QueryWrapper<AgriculturalTrainingDetail>().eq("training_detail_id", body.get("trainingDetailId").toString()));
        return new ResponseResult<Object>(200,"修改培训详情成功",null);
    }

}
